package logic

import (
	"context"
	"errors"
	"newhouse/houserpc/houserpc"
	"newhouse/houserpc/internal/svc"
	"newhouse/model/cache"
	"newhouse/model/mysql"
	"newhouse/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录
func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	err := user.FindUserByUsername(mysql.DB, in.Username)
	if err != nil {
		return nil, errors.New("该用户未注册 禁止登录")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误")
	}

	//短信
	result, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Username).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误")
	}

	//图片
	results, err := cache.Rdb.Get(l.ctx, "captcha"+in.Username).Result()
	if results != in.CaptchaCode {
		return nil, errors.New("图片验证码错误")
	}

	return &houserpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
